package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.ApCollectionService;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author luoTao
 * @project xmsz
 * @date 2024/1/26 09:44:43
 */
@Service
@Slf4j
public class ApCollectionServiceImpl implements ApCollectionService {
    @Autowired
    private CacheService cacheService;

    /**
     * @param dto :
     * @return ResponseResult<?>
     * @author 18297
     * @date 2024/1/26 09:55
     * @description 用户行为，收藏/取消
     */
    @Override
    public ResponseResult<?> collectionBehavior(CollectionBehaviorDto dto) {
        // 参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 收藏/取消收藏
        if (dto.getOperation() == 0) {
            cacheService.hPut("collection_" + user.getId(), dto.getEntryId().toString(), JSON.toJSONString(dto));
        } else if (dto.getOperation() == 1) {
            cacheService.hDelete("collection_" + user.getId(), dto.getEntryId().toString());
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
